package neu.dreamera.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;

import neu.dreamera.R;
import neu.dreamera.utils.AsyncGetDataUtil;
import neu.dreamera.utils.HttpConnectionUtil;
import neu.dreamera.view.ReFlashlistView;

/**
 * Created by root on 16-6-24.
 */
public class PointListActivity extends Activity implements ReFlashlistView.IReflashListener{
    public static final String TAG="PointListActivity";
    ReFlashlistView list;
    ListView listview;
    View view;
    SimpleAdapter listItemAdapter;
    ArrayList<HashMap<String, Object>> listItem=new ArrayList<HashMap<String, Object>>();

    Handler handler = new Handler();
    private final int Update=1;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Log.d(TAG,"onCreate");

        setContentView(R.layout.point_listview);
        list= (ReFlashlistView)findViewById(R.id.listView);


        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                HashMap<String, Object> item = listItem.get(position-1);
                int point_id = (int) item.get("id");
                String name = (String) item.get("name");
                String longitude = (String) item.get("longitude");
                String latitude = (String) item.get("latitude");
                String cross_pictures = (String) item.get("cross_pictures");
                Log.d(TAG,"cross_pictures is"+cross_pictures);
                Intent intent = new Intent();
                intent.setClass(PointListActivity.this, PointActivity.class);
                intent.putExtra("point_id", point_id);
                intent.putExtra("name", name);
                intent.putExtra("longitude", longitude);
                intent.putExtra("latitude", latitude);
                intent.putExtra("cross_pictures", cross_pictures);
                PointListActivity.this.startActivity(intent);
            }
        });

        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                HashMap<String, Object> item = listItem.get(position-1);
                int p=position-1;
                final int item_id = (int) item.get("id");
                new AlertDialog.Builder(PointListActivity.this).setTitle("系统提示")//设置对话框标题
                        .setMessage("Delete this point?")//设置显示的内容
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {//添加确定按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                //new thread to delete
                                new Thread(){
                                    public void run(){
                                        try{
                                            HttpConnectionUtil.doDelete(HttpConnectionUtil.PLACEURL+item_id +"/");
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    if(HttpConnectionUtil.result == "success"){
                                                        listItem.remove(position-1);
                                                        listItemAdapter.notifyDataSetChanged();
                                                        Log.d( TAG,"delete a point" );
                                                    }
                                                }
                                            });

                                        }
                                        catch(Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }.start();

                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener(){//添加返回按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {//响应事件
                                //TODO Auto-generated method stub
                                dialog.dismiss();
                            }
                        }).show();//在按键响应事件中显示此对话框
                return true;
            }
        });


        Button addButton = (Button)findViewById(R.id.addPointbutton);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(PointListActivity.this, AddpointActivity.class);
                PointListActivity.this.startActivity(intent);
                Log.d( TAG,"add a new point" );
            }
        });
    }
    @Override
    public void onStart(){
        super.onStart();
        Log.d(TAG,"onStart");
    }
    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
        setData();
/*
        handler=new Handler(){
            public void HandleMessage(Message Msg) {
                switch (Msg.what){
                    case Update:setData();break;
                    default:break;
                }
            }
        };
*/
    }
    @Override
    public void onPause(){
        super.onPause();
        Log.d(TAG, "onPause");
    }
    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }
    @Override
    public void onRestart(){
        super.onRestart();
        Log.d(TAG,"onRestart");
    }

    public void setData(){
        AsyncGetDataUtil asyncGetDataUtil=new AsyncGetDataUtil();
        String result;
        asyncGetDataUtil.getJSONData();
        result=asyncGetDataUtil.getJSONFromFile();

        try {
            listItem=asyncGetDataUtil.decodeJsonToPoint(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        listItemAdapter = new SimpleAdapter(

                PointListActivity.this,
                listItem,//数据源 为填充数据后的ArrayList类型的对象
                R.layout.point_list_item,//子项的布局.xml文件名
                new String[]{"name"},//这个String数组中的元素就是list对象中的列，list中有几这个数组中就要写几列。
                new int[]{R.id.name}//值是对应XML布局文件中的一个ImageView,三个TextView的id
        );
        listItemAdapter.notifyDataSetChanged();
        list.setInterface(this);
        list.setAdapter(listItemAdapter);
        //生成一个SimpleAdapter类型的变量来填充数据,
        Log.d(TAG,"SetData()");
        Log.d( TAG,"After set: listItem is"+listItem.toString() );
        Log.d( TAG,"After set: result is"+result);
    }
    @Override
    public void onReflash() {

        handler.postDelayed(new Runnable() {
            @Override
            public void run(){
                //TODO Auto-generated method stub
/*
                Message message=new Message();
                message.what=Update;
                handler.sendMessage(message);
*/
                //获取最新数
                //通知界面显示
                //showList(apk_list);
                //通知listview 刷新数据完毕；

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG,"start update");
                        setData();
                    }
                });
                Log.d(TAG,"update finish");
                list.reflashComplete();
            }
        }, 2000);
    }

}
